package com.cloud_notes.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloud_notes.demo.common.exception.CustomException;
import com.cloud_notes.demo.common.pojo.dataobject.UserInfo;
import com.cloud_notes.demo.common.pojo.request.UserLoginRequest;
import com.cloud_notes.demo.common.pojo.response.UserLoginResponse;
import com.cloud_notes.demo.common.utils.JwtUtil;
import com.cloud_notes.demo.mapper.UserInfoMapper;
import com.cloud_notes.demo.service.UserLoginService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserLoginServiceImpl implements UserLoginService {

//    @Autowired
    @Resource(name = "userInfoMapper")//直接根据对象Bean查询
    private UserInfoMapper userInfoMapper;

    @Override
    public UserLoginResponse login(UserLoginRequest userLoginRequest) {
        //根据用户名查寻数据库中是否存在
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getUserName,userLoginRequest.getUserName())
                .eq(UserInfo::getDeleteFlag,0));//还需检查用户是否注销
        if(userInfo == null){
//            return new UserLoginResponse();//返回空对象
            throw new CustomException("用户不存在");//同一异常处理
        }

        //检验密码:在userInfo类中已经校验是否为空
        if(!userInfo.getPassword().equals(userLoginRequest.getPassword())){
            throw new CustomException("密码错误");
        }

        //正确，则响应数据信息
        UserLoginResponse userLoginResponse = new UserLoginResponse();
        userLoginResponse.setUserId(userInfo.getId());

        //jwt载荷部分
        Map<String,Object> map = new HashMap<>();
        map.put("id",userInfo.getId());
        map.put("name",userInfo.getUserName());
        //生成Token
        String key = JwtUtil.genJwt(map);
        userLoginResponse.setToken(key);
        return userLoginResponse;
    }
}
